package com.example.testapp;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.testapp.api.ApiClient;
import com.example.testapp.api.ApiService;
import com.example.testapp.model.RegisterRequest;
import com.example.testapp.model.UserResponse;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterActivity extends Activity {

    private EditText etUsername;
    private EditText etPhoneNumber;
    private EditText etPassword;
    private Button btnRegister;
    private CheckBox cbAgreement;
    private TextView tvAgreementText; // 协议文本引用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // 初始化视图组件
        initViews();

        // 设置箭头图标点击事件（返回登录页面）
        findViewById(R.id.icon_arrow_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed(); // 使用系统返回逻辑
            }
        });

        // 设置协议勾选监听
        setupAgreementCheckbox();

        // 设置注册按钮点击事件
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideKeyboard();
                registerUser();
            }
        });
    }

    /**
     * 初始化视图组件
     */
    private void initViews() {
        etUsername = findViewById(R.id.username);
        etPhoneNumber = findViewById(R.id.phone_number);
        etPassword = findViewById(R.id.password);
        btnRegister = findViewById(R.id.register_button);
        cbAgreement = findViewById(R.id.agreement_checkbox);
        tvAgreementText = findViewById(R.id.agreement_text); // 新增协议文本引用
        // 服务协议
        TextView agreementText1 = findViewById(R.id.agreement_text1);
        // 隐私保护协议
        TextView agreementText2 = findViewById(R.id.agreement_text2);

        // 手机号输入监听
        etPhoneNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    etPassword.requestFocus(); // 自动跳转到密码输入框
                }
            }
        });
        // 设置服务协议和隐私保护协议的点击事件
        agreementText1.setOnClickListener(v -> openAgreement("https://gitee.com/wys_666/android-frontend"));
        agreementText2.setOnClickListener(v -> openAgreement("https://gitee.com/wys_666/android-backend"));
    }

    /**
     * 设置协议勾选监听
     */
    private void setupAgreementCheckbox() {
        cbAgreement.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 勾选时提示
                    Toast.makeText(RegisterActivity.this, "已阅读并同意服务协议", Toast.LENGTH_SHORT).show();
                } else {
                    // 取消勾选时提示
                    Toast.makeText(RegisterActivity.this, "已取消同意服务协议", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 处理用户注册逻辑
     */
    private void registerUser() {
        // 获取输入内容
        String username = etUsername.getText().toString().trim();
        String phoneNumber = etPhoneNumber.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        // 输入验证
        if (TextUtils.isEmpty(username)) {
            etUsername.setError("请输入用户名");
            etUsername.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(phoneNumber)) {
            etPhoneNumber.setError("请输入手机号");
            etPhoneNumber.requestFocus();
            return;
        }

        if (phoneNumber.length() != 11) {
            etPhoneNumber.setError("请输入正确的11位手机号");
            etPhoneNumber.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            etPassword.setError("请输入密码");
            etPassword.requestFocus();
            return;
        }

        if (password.length() < 6) {
            etPassword.setError("密码长度至少为6位");
            etPassword.requestFocus();
            return;
        }

        if (!cbAgreement.isChecked()) {
            Toast.makeText(this, "请先同意服务协议和隐私保护协议", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建注册请求对象
        RegisterRequest request = new RegisterRequest(phoneNumber, username, password);

        // 使用封装好的 ApiClient 获取接口对象
        ApiService api = ApiClient.getClient().create(ApiService.class);

        // 发起异步请求
        api.register(request).enqueue(new Callback<UserResponse>() {
            @Override
            public void onResponse(@NonNull Call<UserResponse> call, @NonNull Response<UserResponse> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(RegisterActivity.this, "注册成功！请登录", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.putExtra("username", username);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(RegisterActivity.this, "注册失败：" + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(@NonNull Call<UserResponse> call, @NonNull Throwable t) {
                Toast.makeText(RegisterActivity.this, "网络异常：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 打开服务协议和隐私保护协议页面
     */
    public void openAgreement(View view) {
        Toast.makeText(this, "打开服务协议和隐私保护协议", Toast.LENGTH_SHORT).show();
        // TODO: 实现打开协议页面的逻辑
    }

    // 点击布局时让输入框失去焦点
    public void clearFocusOnClick(View view) {
        etUsername.clearFocus();
        etPhoneNumber.clearFocus();
        etPassword.clearFocus();
        hideKeyboard();
    }

    // 隐藏软键盘的方法
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
        View view = getCurrentFocus();
        if (view == null) {
            view = new View(this);
        }
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    private void openAgreement(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
    }
}